<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <div class="about-master-container">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change="(e)=>stepVal=e"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="整改回复编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="物资检查记录编码"
                    prop="inspectionCode"
                  >
                    <a-input-search
                      v-model="formData.inspectionCode"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openCheck"
                      @click="openCheck"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="工程名称"
                    prop="constructionTypeId"
                  >
                    <a-select
                      v-model="formData.constructionTypeId"
                      :disabled="state === 3"
                    >
                      <a-select-option
                        v-for="item in getProgrammeArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="发文单位"
                    prop="checkOrgName"
                  >
                    <BaseInput
                      v-model="formData.checkOrgName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="检查人"
                    prop="perList"
                  >
                    <BaseInput
                      v-model="formData.recorderName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="检查时间">
                    <BaseInput
                      v-model="formData.checkDate"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="接收单位">
                    <BaseInput
                      v-model="formData.inspectedUnitName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="接收人"
                    prop="receiverName"
                  >
                    <a-input-search
                      v-model="formData.receiverName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @click="openRecipient"
                      @search="openRecipient"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="完成期限"
                    prop="deadlines"
                  >
                    <a-date-picker
                      v-model="formData.deadlines"
                      value-format="YYYY-MM-DD"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="指定验证人"
                    prop="specVerifierName"
                  >
                    <a-input-search
                      v-model="formData.specVerifierName"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openVerifier"
                      @click="openVerifier"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <a-form-model-item
                    label="整改内容"
                    prop="content"
                  >
                    <BaseTextarea
                      v-model="formData.content"
                      :max-length="5000"
                      :disabled="state === 3"
                      :auto-size="{ minRows: 3, maxRows: 5 }"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div class="pub-next-btn">
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="整改结果">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <rectification-results
              ref="rectificationResults"
              :editable="stepTwoEditAble"
              :row="formData"
            />
            <div class="pub-next-btn">
              <a-button
                v-if="stepTwoEditAble"
                type="primary"
                @click="saveRectification"
              >
                保存
              </a-button>
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                :disabled="!formData.id"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="验收结果">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <acceptance
              ref="acceptance"
              :editable="stepThreeEditAble"
              :row="formData"
            />
            <div class="pub-next-btn">
              <a-button
                v-if="stepThreeEditAble"
                type="primary"
                @click="saveAcceptance"
              >
                保存
              </a-button>
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                :disabled="!formData.id"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[3]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="canUpload"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM17"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div class="pub-header-btn page-btn-right-top">
        <a-button
          v-if="state !== 3"
          :loading="loading"
          type="primary"
          @click="submit"
        >
          提交
        </a-button>
        <a-button
          v-if="showCloseBtn"
          v-checkVisibleInDetail
          type="primary"
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <person-list
        ref="recipientList"
        :other-data="{rootOrgId:inspectedUnitId}"
        :org-id="inspectedUnitId"
        @getPerson="getRecipient"
      />
      <person-list
        ref="verifierList"
        :other-data="{rootOrgId:$currentSubCompany().companyId}"
        :org-id="formData.checkOrgId"
        @getPerson="getVerifier"
      />
      <check
        ref="check"
        @getCheck="getCheck"
      />
    </div>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>
<script>
import rectificationResults from '../components/rectificationResults/rectificationResults'
import check from '../components/check/check'
import acceptance from '../components/acceptance/acceptance'
import { selectOption } from '@/api/material/goods/goods'
import { rectificationAdd, rectificationEdit, audit, addFile, fileList, fileDel, findListByMainId } from '@/api/material/check/rectification'

export default {
  name: 'a' + Date.now(),
  components: {
    rectificationResults,
    check,
    acceptance
  },
  props: {
    stepTwoEditAble: {
      type: Boolean,
      default: false
    },
    stepThreeEditAble: {
      type: Boolean,
      default: false
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepTwoEditAble: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$set(this.activeKey, 1, true)
        }
      }
    },
    stepThreeEditAble: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$set(this.activeKey, 2, true)
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  computed: {
    canUpload() {
      if (this.stepTwoEditAble) {
        return true
      }
      if (this.stepThreeEditAble) {
        return true
      }
      console.log(!!this.$route.query.id)
      if (!!this.$route.query.id) {
        return false
      }
      return this.isAudit ? false : true
    },
    showCloseBtn() {
      if (this.stepTwoEditAble) {
        return false
      }
      if (this.stepThreeEditAble) {
        return false
      }
      return true
    }
  },
  data() {
    return {
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      stepVal: 0,
      state: Number(this.$route.query.state),
      isSubmit: false,
      row: this.$route.query.row,
      formData: {
        createTime: this.getNowTime(),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        code: '',
        inspectionCode: '',
        constructionTypeId: '',
        checkOrgName: '',
        recorderName: '',
        checkDate: null,
        inspectedUnitName: '',
        receiverName: '',
        deadlines: null,
        specVerifierName: '',
        content: '',
        inspectionId: '',
        receiverId: '',
        specVerifierId: ''
      },
      rules: {
        inspectionCode: { required: true, message: '物资检查记录编码不能为空', trigger: 'change' },
        receiverName: { required: true, message: '接收人不能为空', trigger: 'change' },
        deadlines: { required: true, message: '完成期限不能为空', trigger: 'change' },
        specVerifierName: { required: true, message: '指定验证人不能为空', trigger: 'change' },
        content: { required: true, message: '整改内容不能为空', trigger: 'blur' }
      },
      isNext: false,
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      getProgrammeArr: [],
      checkOrgId: null,
      inspectedUnitId: null,
       //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  mounted: async function () {
    this.getProgramme()
    if (this.state && this.state !== 1) {
      this.formData.id = this.$route.query.id
      this.getEditInfo()
      this.isSubmit = true
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('mm_check_rectification')
  },
  methods: {
    previous: function () {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    async getProgramme() {
      let res = await selectOption({ type: 18 })
      if (res.code === 200) {
        this.getProgrammeArr = res.data
        this.formData.constructionTypeId = res.data[0].id
      }
    },
    saveRectification: function () {
      this.$refs.rectificationResults.temporaryStorage()
    },
    saveAcceptance: function () {
      this.$refs.acceptance.temporaryStorage()
    },
    getCheck: function (row) {
      this.$console(row)
      this.formData.inspectionCode = row.code
      this.formData.inspectionId = row.id
      this.formData.checkOrgName = row.checkOrgName
      this.formData.checkOrgId = row.checkOrgId
      this.formData.recorderName = row.recorderName
      this.formData.checkDate = row.checkDate
      this.formData.inspectedUnitName = row.inspectedUnitName
      this.inspectedUnitId = row.inspectedUnitId
    },
    openCheck: function () {
      this.$refs.check.open()
    },
    openRecipient: function () {
      if (this.formData.inspectionCode) {
        this.$refs.recipientList.open()
      } else {
        this.$noticeWarning('请选择物资检查记录编码')
      }
    },
    getRecipient: function (row) {
      this.formData.receiverName = row.name
      this.formData.receiverId = row.userId
    },
    openVerifier: function () {
      this.$refs.verifierList.open()
    },
    getVerifier: function (row) {
      this.formData.specVerifierName = row.name
      this.formData.specVerifierId = row.userId
    },
    stepChange: function (val) {
      if (!this.formData.id && !this.isAudit) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    // 获取编辑回显数据
    async getEditInfo() {
      this.loading = true
      let res = await findListByMainId({ id: this.formData.id })
      if (res.code === 200) {
        this.formData = this.$assign(this.formData, res.data)
      }
      this.loading = false
    },
    submit() {
      // this.save('approve');
      this.setProcessConfig = null;
      if (this.isSubmit) {
          this.submitApprovalConfirm(this.isSubmit?this.processConfig:6,(flag)=>{
          if(!flag) {
            this.loading = false
            return
          }
            this.loading = true
            audit({
              baseId: this.formData.id,
              auditStatus: this.formData.auditStatus
            }).then((res) => {
              this.$message.success('提交成功')
              this.loading = false
              //提交时，返回id
              this.businessId = this.formData.id;
              this.setProcessConfig = this.processConfig;
              //this.$router.push({ path: '/material/check/rectification' })
            })
          })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    temporaryStorage(isNext) {
      if (this.state === 3) {
        this.next()
        return
      }
      this.$refs.ruleForm.validate((valid, object) => {
        if (valid) {
          if (this.formData.receiverId === this.formData.specVerifierId) {
            return this.$message.error('接收人和指定验证人不能相同')
          }
          this.loading = true
          delete this.formData.perList
          if (this.state === 2 || this.formData.id) {
            rectificationEdit(this.formData).then((res) => {
              if (res.code === 200) {
                this.$message.success('暂存成功')
                this.isSubmit = true
                if (isNext) {
                  this.next()
                }
              }
              this.loading = false
            })
          } else {
            rectificationAdd(this.formData).then(async (res) => {
              if (res.code === 200) {
                this.$message.success('暂存成功')
                this.isSubmit = true
                this.formData.id = res.data.id
                await this.getEditInfo()
                if (isNext) {
                  this.next()
                }
              }
              this.loading = false
            })
          }
        } else {
          return false
        }
      })
    },
    next: function (val) {
      this.isNext = true
      this.stepVal++
    }
  }
}
</script>
